/**
 * 将前端请求中的参数转换成字符串，以便签名
 * 输入：
 * let params = {
        categoryId: "asdqwe",
        pageSize: 10,
        pageNum: true,
        students: [
            {
                id: '123',
                name: '456',},
            {
                id: '123',
                name: '456',}
            ],
        student: {
            id: '123',
            name: '456',
            friends:[
                {
                    d:'awer',
                    name: 'qwer'
                },
                {
                    d:'vcasd',
                    name: 'awsbr'
                }
            ]
        }
    }
    输出：
    categoryId=asdqwe&pageNum=true&pageSize=10&student[friends][0][d]=awer&student[friends][0][name]=qwer&student[friends][1][d]=vcasd&student[friends][1][name]=awsbr&student[id]=123&student[name]=456&students[0][id]=123&students[0][name]=456&students[1][id]=123&students[1][name]=456
 * @param {} params 
 */
function paramsToRequestStr (params) {
  var str = "";
  for (var item in params) {
      if (isBlank(params[item])) {
          continue;
      }
      str += "&" + getParamStr(item, params[item]);
  }
  str = str.substring(1);
  str = str.split('&').sort().join('&');
  return str;
}

function getParamStr(key, value) {
  if (typeof value == "object") {
      if (Array.isArray(value)) {
          var arr = [];
          for (var i = 0; i < value.length; i++) {
              arr.push(getParamStr(key + "[" + i + "]", value[i]));
          }
          return arr.join("&");
      } else {
          var arr = [];
          for (var item in value) {
              arr.push(getParamStr(key + "[" + item + "]", value[item]))
          }
          return arr.join("&");
      }
  } else {
      return key + "=" + value;
  }
}

function isBlank(value) {
    return !/\S/.test(value) || '' === value
}

module.exports = {
  paramsToRequestStr: paramsToRequestStr
}
